package com.han.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Properties;

/**
 * 类路径资源加载工具类
 *
 * @author han
 * @date 2022/11/21
 */
public class ClassPathResourceLocalUtil {

    /**
     * 从指定路径获取JSON并转换为List
     * @param path json文件路径
     * @param elementType List元素类型
     */
    public static  <T> List<T> getListFromJson(String path, Class<T> elementType) {
        ClassPathResource resource = getClassPathResource(path);
        String jsonStr = IoUtil.read(resource.getStream(), Charset.forName("UTF-8"));
        JSONArray jsonArray = new JSONArray(jsonStr);
        return JSONUtil.toList(jsonArray, elementType);
    }

    public static Properties getProperties(String path) {
        ClassPathResource resource = getClassPathResource(path);
        Properties prop = new Properties();
        InputStream stream = null;
        try {
            stream = resource.getStream();
            prop.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IoUtil.close(stream);
        }
        return prop;
    }
    public static ClassPathResource getClassPathResource(String path){
        ClassPathResource resource = new ClassPathResource(path);
        return resource;
    }
    public static File getFile(String path){
        return getClassPathResource(path).getFile();
    }

}